package com.luminous.aether.interceptor;

import com.luminous.aether.exception.AetherException;
import com.luminous.aether.constants.AetherErrorMessageConstants;
import com.luminous.aether.constants.HeaderKeyConstants;
import com.luminous.aether.kits.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 请求统一拦截器
 *
 * @author Luminous.X
 * @since 0.0.1-SNAPSHOT
 */
@Component
@SuppressWarnings("unused")
public class RequestHeaderInterceptor implements HandlerInterceptor {
    /**
     * Redis客户端
     */
    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 构造器注入
     *
     * @param redisTemplate Redis客户端
     */
    public RequestHeaderInterceptor(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 请求前置处理
     *
     * @param request  请求头
     * @param response 响应头
     * @param handler  处理对象
     * @return 是否通过
     */
    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        // 请求头中获取token
        String token = request.getHeader(HeaderKeyConstants.TOKEN_HEADER);
        // 判断token是否合法
        if (StringUtil.isBlank(token) || !verifyToken(token)) {
            throw new AetherException(AetherErrorMessageConstants.USER_STATUS_EXPIRE);
        }
        // 根据token获取当前用户信息，并将用户信息存储到线程变量中

        return true;
    }

    /**
     * 判断该token是否合法
     *
     * @param token token
     * @return token是否合法
     */
    private boolean verifyToken(String token) {
        return redisTemplate.hasKey("Authorization:" + token);
    }
}
